package com.example.demo.suanfa;

import java.io.*;

/**
 * @author <a href="mailto:zhouyong@cqyyt.com">user</a>
 * @version 1.0
 * @date 2020/7/8 21:45
 * 稀疏数组
 */
public class XiShusuanfa {


    public static void main(String[] args) throws IOException {
        //自定义一个稀疏数组
        int chessArr[][] = new int[11][11];
        //为稀疏数组进行赋值
        chessArr[1][2] = 1;
        chessArr[2][3] = 2;
        System.out.println("遍历原始的二维数组");
        for( int[] row : chessArr){
            for (int zy : row){
                System.out.printf("%d\t",zy);
            }
            System.out.println();
        }

        //提取二维数组的有效数字
        int sum = 0;
        for (int i = 0; i < chessArr.length; i++) {
            for (int j = 0; j < chessArr[i].length; j++) {
                if (chessArr[i][j] != 0){
                    sum++;
                }
            }
        }
        System.out.println("sum="+sum);
        //根据有效数字定义稀疏数组
        int xishu[][] = new int[sum+1][3];
        //对稀疏数组进行数据封装
        xishu[0][0] = 11;
        xishu[0][1] = 11;
        xishu[0][2] = sum;
        int max = 0;
        for (int i = 0; i < chessArr.length; i++) {
            for (int j = 0; j < chessArr[i].length; j++) {
                if (chessArr[i][j] != 0){
                    max++;
                    xishu[max][0] = i;
                    xishu[max][1] = j;
                    xishu[max][2] = chessArr[i][j];
                }
            }
        }
        System.out.println("对稀疏数组进行遍历");
        for (int[] row : xishu){
            for (int zy : row){
                System.out.printf("%d\t",zy);
            }
            System.out.println();
        }
        //对稀疏数组进行还原
        int huanyuan[][] = new int[xishu[0][0]][xishu[0][1]];
        for (int i = 0; i < xishu[0][2]; i++) {
            huanyuan[xishu[i+1][0]][xishu[i+1][1]] = xishu[i+1][2];
        }
        System.out.println("对还原数组进行遍历");
        for (int[] row : huanyuan){
            for (int zy : row){
                System.out.printf("%d\t",zy);
            }
            System.out.println();
        }
//        System.out.println("io");

        File file = new File("C:\\Users\\user\\Desktop\\工厂\\笔记\\zzz.txt");  //存放数组数据的文件

        FileWriter os = new FileWriter(file);  //文件写入流
        int[][] bytes = xishu;
        for (int i = 0; i < bytes.length; i++) {
            for (int j = 0; j < bytes[i].length; j++) {
                os.write(bytes[i][j]);
            }
        }
        os.flush();
        os.close();
    }



}
